package org.nokatag.system;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.noka.select.Select;

public class DataUtil {
	/**
	 * 关闭session
	 * @param session
	 */
	private static void closeSession(Session session){
		try{
			if(null!=session && Concest.IS_AUTO_CLOSE_HIBERNATE_ESSION){
				session.close();
			}
		}catch(Exception e){}
	}
	/**
	 * 开始事务
	 */
	public static void beginTransaction(){
		ServletNokaContext.setTransactionBreak(false);
		if(null!=ServletNokaContext.getHibernateSession()){
			ServletNokaContext.setTransaction(ServletNokaContext.getHibernateSession().beginTransaction());
		}
	}
	/**
	 * <p>@Description 清空连接</p>
	 * <p>author rebin </p>
	 * <p>@Time 上午9:13:23</p>
	 * <p>xiefangjian@163.com</p>
	 */
	public static void ExceptionClear(){
		try{
			ServletNokaContext.setTransaction(null);
			ServletNokaContext.setTransactionBreak(false);
			closeSession(ServletNokaContext.getHibernateSession());
		}catch(Exception e){}
	}
	/**
	 * 提交事务，出错会自动回滚
	 */
	public static void commitTransaction(){
		if(ServletNokaContext.getTransaction()!=null && ServletNokaContext.getTransactionBreak()){
			ServletNokaContext.getTransaction().rollback();//有错误，回滚数据
		}else if(ServletNokaContext.getTransaction()!=null && !ServletNokaContext.getTransactionBreak()){
			ServletNokaContext.getTransaction().commit();//没有错误提交数据
		}
		ServletNokaContext.setTransactionBreak(false);
		ServletNokaContext.setTransaction(null);
		closeSession(ServletNokaContext.getHibernateSession());
	}
	/**
	 * <br>@查入数据</br>
	 * <br>@param Object</br>
	 * <br>@return serializable</br>
	 */
	public static Serializable insert(Object object){
		if(ServletNokaContext.getHibernateSession()!=null && ServletNokaContext.getTransaction()!=null){
			try{
				return ServletNokaContext.getHibernateSession().save(object);
			}catch(Exception se){
				ServletNokaContext.setTransactionBreak(true);
				BugInfoWrint.Print(se);
				return 0;
			}
		}
		Session session = ServletNokaContext.getHibernateSession();
		session.clear();
		Transaction tt = null;
		Serializable serializable = null;
		try{
			tt = session.beginTransaction();
			serializable = session.save(object);
			tt.commit();
		}catch(Exception se){
			BugInfoWrint.Print(se);
			if(tt!=null)
				tt.rollback();
		}
		closeSession(session);
		return serializable;
	}
	/**
	 * <br>批量查入数据</br>
	 * <br>@param List<Object></br>
	 * <br>@return Serializable<br>
	 */
	public static Serializable insertList(List<?> objectlist){
		if(ServletNokaContext.getHibernateSession()!=null && ServletNokaContext.getTransaction()!=null){
			try{
				for(Object object:objectlist)
					ServletNokaContext.getHibernateSession().save(object);
				return 1;
			}catch(Exception se){
				ServletNokaContext.setTransactionBreak(true);
				BugInfoWrint.Print(se);
				return 0;
			}
		}
		Session session = ServletNokaContext.getHibernateSession();
		session.clear();
		Transaction tt = null;
		Serializable serializable = null;
		try{
			tt = session.beginTransaction();
			for(Object object:objectlist)
				serializable = session.save(object);
			tt.commit();
		}catch(Exception se){
			BugInfoWrint.Print(se);
			if(tt!=null)
				tt.rollback();
		}
		closeSession(session);
		return serializable;
	}
	/**
	 * <br>删除数据<br>
	 * <br>@param Object<br>
	 * <br>@return boolean,成功返回true,失败返回false<br>
	 */
	public static boolean delete(Object object){
		if(ServletNokaContext.getHibernateSession()!=null && ServletNokaContext.getTransaction()!=null){
			try{
				ServletNokaContext.getHibernateSession().delete(object);
				return true;
			}catch(Exception se){
				ServletNokaContext.setTransactionBreak(true);
				BugInfoWrint.Print(se);
				return false;
			}
		}
		Session session = ServletNokaContext.getHibernateSession();
		session.clear();
		Transaction tt = null;
		boolean issussces = false;
		try{
			tt = session.beginTransaction();
			session.delete(object);
			tt.commit();
			issussces=true;
		}catch(Exception se){
			BugInfoWrint.Print(se);
			if(tt!=null)
				tt.rollback();
		}
		closeSession(session);
		return issussces;
	}
	/**
	 * <br>批量删除数据<br>
	 * <br>@param List<Object><br>
	 * <br>@return boolean,成功返回true,失败返回false<br>
	 */
	public static boolean deleteList(List<?> objectlist){
		if(ServletNokaContext.getHibernateSession()!=null && ServletNokaContext.getTransaction()!=null){
			try{
				for(Object object:objectlist)
					ServletNokaContext.getHibernateSession().delete(object);
				return true;
			}catch(Exception se){
				ServletNokaContext.setTransactionBreak(true);
				BugInfoWrint.Print(se);
				return false;
			}
		}
		Session session = ServletNokaContext.getHibernateSession();
		session.clear();
		Transaction tt = null;
		boolean issussces = false;
		try{
			tt = session.beginTransaction();
			for(Object object:objectlist)
				session.delete(object);
			tt.commit();
			issussces=true;
		}catch(Exception se){
			BugInfoWrint.Print(se);
			if(tt!=null)
				tt.rollback();
		}
		closeSession(session);
		return issussces;
	}
	/**
	 * <br>修改数据<br>
	 * <br>@param Object<br>
	 * <br>@return boolean,成功返回true,失败返回false<br>
	 */
	public static boolean update(Object object){
		if(ServletNokaContext.getHibernateSession()!=null && ServletNokaContext.getTransaction()!=null){
			try{
				ServletNokaContext.getHibernateSession().update(object);
				return true;
			}catch(Exception se){
				ServletNokaContext.setTransactionBreak(true);
				BugInfoWrint.Print(se);
				return false;
			}
		}
		Session session = ServletNokaContext.getHibernateSession();
		session.clear();
		Transaction tt = null;
		boolean issussces = false;
		try{
			tt = session.beginTransaction();
			session.update(object);
			tt.commit();
			issussces=true;
		}catch(Exception se){
			BugInfoWrint.Print(se);
			if(tt!=null)
				tt.rollback();
		}
		closeSession(session);
		return issussces;
	}
	/**
	 * <br>修改数据<br>
	 * <br>@param List<Object><br>
	 * <br>@return boolean,成功返回true,失败返回false<br>
	 */
	public static boolean updateList(List<?> objectlist){
		if(ServletNokaContext.getHibernateSession()!=null && ServletNokaContext.getTransaction()!=null){
			try{
			for(Object object:objectlist)
				ServletNokaContext.getHibernateSession().update(object);
				return true;
			}catch(Exception se){
				ServletNokaContext.setTransactionBreak(true);
				BugInfoWrint.Print(se);
				return false;
			}
		}
		Session session = ServletNokaContext.getHibernateSession();
		session.clear();
		Transaction tt = null;
		boolean issussces = false;
		try{
			tt = session.beginTransaction();
			for(Object object:objectlist)
				session.update(object);
			tt.commit();
			issussces=true;
		}catch(Exception se){
			BugInfoWrint.Print(se);
			if(tt!=null)
				tt.rollback();
		}
		closeSession(session);
		return issussces;
	}
	/**
	 * <br>查询数据<br>
	 * <br>@param String<br>
	 * <br>@return List<br>
	 */
	@SuppressWarnings("unchecked")
	public static <T> List<T> objectList(String hsql){
		List<T> dlist = null;
		try{
			Session session = ServletNokaContext.getHibernateSession();
			session.clear();
			Query query = session.createQuery(hsql);
			dlist = query.list();
			if(dlist!=null)
				dlist.toString();//防止空对象
			closeSession(session);
		}catch(Exception se){
			BugInfoWrint.Print(se);
		}
		return dlist;
	}
	/**
	 * <br>查询数据<br>
	 * <br>@param String<br>
	 * <br>@param int 开始记录数<br>
	 * <br>@param int 最大返回数<br>
	 * <br>@return List<br>
	 */
	@SuppressWarnings("unchecked")
	public static <T> List<T> objectList(String hsql,int start,int max){
		List<T> dlist =null;
		try{
			Session session = ServletNokaContext.getHibernateSession();
			session.clear();
			Query query = session.createQuery(hsql);
			query.setFirstResult(start);
			query.setMaxResults(max);
			dlist = query.list();
			if(dlist!=null)
				dlist.toString();//防止空对象
			closeSession(session);
		}catch(Exception se){
			BugInfoWrint.Print(se);
		}
		return dlist;
	}
	/**
	 * <br>查询数据<br>
	 * <br>@param String<br>
	 * <br>@return Query<br>
	 */
	/*
	public static Query query(String hsql){
		Session session = ServletNokaContext.getHibernateSession();;
		session.clear();
		Query query = session.createQuery(hsql);
		return query;
	}
	*/
	/**
	 * <br>查询数据<br>
	 * <br>@param String<br>
	 * <br>@return Object<br>
	 */
	@SuppressWarnings("unchecked")
	public static <T> T object(String hsql){
		Object object = null;
		try{
			Session session = ServletNokaContext.getHibernateSession();
			session.clear();
			Query query = session.createQuery(hsql);
			List<?> utit = query.list();
	        if(null!=utit && !utit.isEmpty()){
	        	object = utit.get(0);
	        }
	        if(object!=null)
	        	object.toString();//防止空对象
	        closeSession(session);
		}catch(Exception se){
			BugInfoWrint.Print(se);
		}
		return (T)object;
	}
	
	/**
	 * <br>查询数据<br>
	 * <br>@param String<br>
	 * <br>@param Integer 当前页<br>
	 * <br>@param Integer 页面显示多少条<br>
	 * <br>@return Object<br>
	 */
	public static DataPage dataPage(String hsql,Integer newpage,Integer pagesize){
		Session session = ServletNokaContext.getHibernateSession();
		session.clear();
		DataPage dataPage = new DataPage();
		Query query = session.createQuery(hsql);
		Query query2 = session.createQuery(hsql);
		//------------分页计算-----------------------------------
		
		Integer rows = query.list().size();//总记录行数
		Integer pages = (rows%pagesize==0)?(rows/pagesize):(rows/pagesize+1);//总页数
		
		if(newpage<1)
			newpage=1;
		else if(newpage>pages)
			newpage = pages;
		
		Integer pagesartrows = (newpage-1)*pagesize;//第几页的开始记录数
		if(rows>0){
			query2.setFirstResult(pagesartrows);
			query2.setMaxResults(pagesize);
			dataPage.setRows(rows);
			dataPage.setPagesize(pagesize);
			dataPage.setPages(pages);
			dataPage.setNewpage(newpage);
			dataPage.setDataobject(query2.list());
			dataPage.setNewstartrows(pagesartrows+1);
			dataPage.setNewendrows(pagesartrows+dataPage.getDataobject().size());
		}else{
			dataPage.setRows(0);
			dataPage.setPagesize(20);
			dataPage.setPages(0);
			dataPage.setNewpage(0);
			dataPage.setNewstartrows(0);
			dataPage.setNewendrows(0);
		}
		closeSession(session);
		//------------------------------------------------------
		return dataPage;
	}
	/**
	 * <br>查询数据<br>
	 * <br>@param String<br>
	 * <br>@param Integer 列数<br>
	 * <br>@param Integer 当前页<br>
	 * <br>@param Integer 页面显示多少条<br>
	 * <br>@return DataPageList<br>
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static DataPageList  dataPagelist(String hsql,Integer cells,Integer newpage,Integer pagesize){
		Session session = ServletNokaContext.getHibernateSession();;
		session.clear();
		DataPageList dataPage = new DataPageList();
		Query query = session.createQuery(hsql);
		Query query2 = session.createQuery(hsql);
		List  datalists = new ArrayList();
		//------------分页计算-----------------------------------
		Integer rows = query.list().size();//总记录行数
		Integer pages = (rows%pagesize==0)?(rows/pagesize):(rows/pagesize+1);//总页数
		if(newpage<1)
			newpage=1;
		else if(newpage>pages)
			newpage = pages;
		
		Integer pagesartrows = (newpage-1)*pagesize;//第几页的开始记录数
		if(rows>0){
			query2.setFirstResult(pagesartrows);
			query2.setMaxResults(pagesize);
			dataPage.setRows(rows);
			dataPage.setPagesize(pagesize);
			dataPage.setPages(pages);
			dataPage.setNewpage(newpage);
			datalists=query2.list();
		}else{
			dataPage.setRows(0);
			dataPage.setPagesize(20);
			dataPage.setPages(0);
			dataPage.setNewpage(0);
		}
		List  productilists = new ArrayList();
		if(rows>0){
			for(int i=0;i<datalists.size();i+=cells){//行
				List productItemlists = new ArrayList(); 
				for(int a=i;a<i+cells && a<datalists.size();a++){
					productItemlists.add(datalists.get(a));
				}
				productilists.add(productItemlists);
			}
			dataPage.setDataobject(productilists);
		}
		closeSession(session);
		//------------------------------------------------------
		return dataPage;
	}
	
	//================================================================================================
	/**
	 * <br>查询数据</br>
	 * <br>@param String</br>
	 * <br>@param List<DataWhere></br>
	 * <br>@return List</br>
	 */
	@SuppressWarnings("unchecked")
	public static <T> List<T> objectList(String hsql,List<DataWhere> where){
		List<T> dlist=null;
		try{
			Session session = ServletNokaContext.getHibernateSession();
			session.clear();
			Query query = session.createQuery(hsql);
			setWhere(query,where);
			dlist = query.list();
			if(dlist!=null)
				dlist.toString();//防止空对象
			closeSession(session);
		}catch(Exception se){
			BugInfoWrint.Print(se);
		}
		return dlist;
	}
	/**
	 * <br>查询数据</br>
	 * <br>@param String</br>
	 * <br>@param List<DataWhere></br>
	 * <br>@param int 开始记录</br>
	 * <br>@param int 返回最大记录</br>
	 * <br>@return List</br>
	 */
	@SuppressWarnings("unchecked")
	public static <T> List<T> objectList(String hsql,List<DataWhere> where,int start,int max){
		List<T> dlist=null;
		try{
			Session session = ServletNokaContext.getHibernateSession();
			session.clear();
			Query query = session.createQuery(hsql);
			setWhere(query,where);
			query.setFirstResult(start);
			query.setMaxResults(max);
			dlist = query.list();
			if(dlist!=null)
				dlist.toString();//防止空对象
			closeSession(session);
		}catch(Exception se){
			BugInfoWrint.Print(se);
		}
		return dlist;
	}
	/**
	 * <br>查询数据</br>
	 * <br>@param String</br>
	 * <br>@param List<DataWhere></br>
	 * <br>@return Object</br>
	 */
	
	@SuppressWarnings("unchecked")
	public static <T> T object(String hsql,List<DataWhere> where){
		Object obj = null;
		try{
			Session session = ServletNokaContext.getHibernateSession();
			session.clear();
			Query query = session.createQuery(hsql);
			setWhere(query,where);
			List<?> utit = query.list();
	        if(null!=utit && !utit.isEmpty()){
	        	obj = utit.get(0);
	        }
	        if(obj!=null)
	        	obj.toString();//防止空对象
	        closeSession(session);
		}catch(Exception se){
			BugInfoWrint.Print(se);
		}
		return (T)obj;
	}
	
	/**
	 * <br>查询数据</br>
	 * <br>@param String</br>
	 * <br>@param List<DataWhere></br>
	 * <br>@param Integer 当前页</br>
	 * <br>@param Integer 页面显示多少条<DataWhere></br>
	 * <br>@return Object</br>
	 */
	public static DataPage dataPage(String hsql,List<DataWhere> where,Integer newpage,Integer pagesize){
		Session session = ServletNokaContext.getHibernateSession();
		session.clear();
		DataPage dataPage = new DataPage();
		Query query = session.createQuery(hsql);
		setWhere(query,where);
		Query query2 = session.createQuery(hsql);
		setWhere(query2,where);
		//------------分页计算-----------------------------------
		
		Integer rows = query.list().size();//总记录行数
		Integer pages = (rows%pagesize==0)?(rows/pagesize):(rows/pagesize+1);//总页数
		
		if(newpage<1)
			newpage=1;
		else if(newpage>pages)
			newpage = pages;
		
		Integer pagesartrows = (newpage-1)*pagesize;//第几页的开始记录数
		if(rows>0){
			query2.setFirstResult(pagesartrows);
			query2.setMaxResults(pagesize);
			dataPage.setRows(rows);
			dataPage.setPagesize(pagesize);
			dataPage.setPages(pages);
			dataPage.setNewpage(newpage);
			dataPage.setDataobject(query2.list());
			dataPage.setNewstartrows(pagesartrows+1);
			dataPage.setNewendrows(pagesartrows+dataPage.getDataobject().size());
		}else{
			dataPage.setRows(0);
			dataPage.setPagesize(20);
			dataPage.setPages(0);
			dataPage.setNewpage(0);
			dataPage.setNewstartrows(0);
			dataPage.setNewendrows(0);
		}
		closeSession(session);
		//------------------------------------------------------
		return dataPage;
	}
	/**
	 * 列表显示
	 * @param hsql
	 * @param newpage
	 * @param pagesize
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static DataPageList  dataPagelist(String hsql,List<DataWhere> where,Integer cells,Integer newpage,Integer pagesize){
		Session session = ServletNokaContext.getHibernateSession();;
		session.clear();
		DataPageList dataPage = new DataPageList();
		Query query = session.createQuery(hsql);
		setWhere(query,where);
		Query query2 = session.createQuery(hsql);
		setWhere(query2,where);
		List datalists = new ArrayList();
		//------------分页计算-----------------------------------
		Integer rows = query.list().size();//总记录行数
		Integer pages = (rows%pagesize==0)?(rows/pagesize):(rows/pagesize+1);//总页数
		if(newpage<1)
			newpage=1;
		else if(newpage>pages)
			newpage = pages;
		
		Integer pagesartrows = (newpage-1)*pagesize;//第几页的开始记录数
		if(rows>0){
			query2.setFirstResult(pagesartrows);
			query2.setMaxResults(pagesize);
			dataPage.setRows(rows);
			dataPage.setPagesize(pagesize);
			dataPage.setPages(pages);
			dataPage.setNewpage(newpage);
			datalists=query2.list();
		}else{
			dataPage.setRows(0);
			dataPage.setPagesize(20);
			dataPage.setPages(0);
			dataPage.setNewpage(0);
		}
		List  productilists = new ArrayList();
		if(rows>0){
			for(int i=0;i<datalists.size();i+=cells){//行
				List productItemlists = new ArrayList(); 
				for(int a=i;a<i+cells && a<datalists.size();a++){
					productItemlists.add(datalists.get(a));
				}
				productilists.add(productItemlists);
			}
			dataPage.setDataobject(productilists);
		}
		closeSession(session);
		//------------------------------------------------------
		return dataPage;
	}
	//=============条件设置===========================================
	private static void setWhere(Query query,List<DataWhere> where){
		if(where==null || where.isEmpty())
			return ;
		for(DataWhere dw :where){
			switch(dw.getType()){
				case DataWhere.BOOLEAN:query.setBoolean(dw.getTName(),dw.getTBoolean());
				break;
				case DataWhere.CALENDAR:query.setCalendar(dw.getTName(),dw.getTCalendar());
				break;
				case DataWhere.DATE:query.setDate(dw.getTName(),dw.getTDate());
				break;
				case DataWhere.DOUBLE:query.setDouble(dw.getTName(),dw.getTDouble());
				break;
				case DataWhere.FLOAT:query.setFloat(dw.getTName(),dw.getTFloat());
				break;
				case DataWhere.INTEGER:query.setInteger(dw.getTName(),dw.getTInteger());
				break;
				case DataWhere.LONG:query.setLong(dw.getTName(),dw.getTLong());
				break;
				case DataWhere.SHORT:query.setShort(dw.getTName(),dw.getTShort());
				break;
				case DataWhere.STRING:query.setString(dw.getTName(),dw.getTString());
				break;
				case DataWhere.TIME:query.setTime(dw.getTName(),dw.getTTime());
				break;
				case DataWhere.LIST:query.setParameterList(dw.getTName(),dw.getList());
				break;
				case DataWhere.ARRAY:query.setParameterList(dw.getTName(),dw.getArray());
				break;
			}
		}
	}
	
	public static void main(String[] args){
		List<Select> treeList = DataUtil.objectList("from DeptItem where dlvie ");
		treeList.get(0);
	}
}